import { removeTempMapFactor } from '@/utils'
import { ElMessage } from 'element-plus'
import type { OperationType } from './RightLayerManager.module'
export function initFetchData(props: any, context?: any) {
  const { plotName, layerOperationConfirmData, currentCheckLayerList, companyInfo } =
    toRefs(context)

  const handleLayerManageOperation = (type: string) => {
    if (type === 'cancel') {
      // 取消操作： 清空 图层操作数据
      props.layerOperationConfirmData = null
    } else if (type === 'plot') {
      // 进入标绘页面, 先判断名称是否为空
      if (plotName.value.replace(/^ +| +$/g, '') !== '') {
        // 先将添加/编辑信息上传到接口, TODO 在将图层所有要素进行上图,
        insertUpdateLayerInfo()
      } else {
        ElMessage.error('请输入标绘图名称')
      }
    }
  }

  watch(
    () => layerOperationConfirmData.value,
    (newV: OperationType) => {
      if (newV?.type === 'add') {
        plotName.value = ''
      } else if (newV?.type === 'edit') {
        plotName.value = currentCheckLayerList.value[0]?.bhtmc
      }
    }
  )

  function insertUpdateLayerInfo() {
    // firefightPlotStore.attribute.cjid = currentCheckLayerList.value[0].id //保存采集id
    const params = [
      {
        bhtmc: plotName.value,
        id: layerOperationConfirmData.value.type === 'add' ? '' : currentCheckLayerList.value[0].id,
        qyid: companyInfo.value.id,
        qymc: companyInfo.value.qymc,
        sfyx: 1,
      },
    ]
    const operationSuccessTip =
      layerOperationConfirmData.value.type === 'add' ? '添加成功' : '编辑成功'
    const operationErrorTip =
      layerOperationConfirmData.value.type === 'add' ? '添加失败' : '编辑失败'

    updateLayerInfo(params)
      .then((res: any) => {
        ElMessage.success(operationSuccessTip)
        props.layerOperationFlag = true // 图层操作
        props.isFirefightPlotFlag = true // 进入标绘状态
        props.returnBackLayerControlFlag = false // 从图层管理页面标记到作战标绘页面
        // 新增图层要清除
        if (layerOperationConfirmData.value.type === 'add') {
          clearCheckLayerList()
          props.currentCheckLayerList = res
        }
        props.layerOperationConfirmData = null // 将图层确认数据清空
      })
      .catch((e: any) => {
        console.log('operationErrorTip', e)
        ElMessage.error(operationErrorTip + '，请重新操作')
      })
  }
  /** 清除选中图层信息 */
  function clearCheckLayerList() {
    props.currentCheckLayerList?.forEach((item: any) => {
      removeTempMapFactor(item.id)
    })
  }

  return {
    handleLayerManageOperation,
  }
}
